<template>
	<div id="clue_add" class="dialog animated"  :class="open? 'fadeIn':'fadeOut'"
		 v-show="show" :style="{visibility:(visible?'visible':'hidden')}">
		 
		<div class="panel animated" :class="open? 'zoomIn':''">
			<div class="title">
				新增线索
				<div class="close" @click="cancel()"></div>
			</div>
			<div class="form">
				<div class="row_1">
					<label class="must">*</label>
					<label class="label">孩子姓名</label>
					<el-input v-model="param.realName" id="realName" class="input" clearable></el-input>
					&emsp;
					
					<label class="must"></label>
					<label class="label" style="width: 0.6rem;">性别</label>
					<div class="radio_group">
						<label class="radio" v-for="item,index in gender" @click="param.gender = item.value">
							<span class="radio_circle" :class="item.value==param.gender? 'radio_active' : ''"></span>
							<span class="radio_name">{{item.name}}</span>
						</label>
					</div>
					
				</div>
				
				<div class="row_2">
					<label class="must"></label>
					<label class="label">年级</label>
					<el-select v-model="param.grade" class="input" placeholder="" clearable>
					    <el-option v-for="item in gradeMode" :key="item.value"
					      		   :label="item.name" :value="item.value">
					    </el-option>
					</el-select>
					&emsp;
					
					<label class="must"></label>
					<label class="label">学校</label>
					<el-input v-model="param.kindergarten" id="kindergarten" class="input" maxLength="10" clearable></el-input>
					&emsp;
					
					<label class="label">出生年月</label>
					<el-date-picker v-model="param.birthday" value-format="yyyy-MM-dd"
						 type="month" class="input" id="birthday" clearable :picker-options="pickerOptions">
				    </el-date-picker>
				</div>
				
				<div class="row_3" v-for="item,index in param.parentData">
					<label class="must"></label>
					<label class="label">家长姓名</label>
					<el-input v-model="item.parentName" class="parentName" style="width: 1.3rem;" clearable></el-input>
					<el-select v-model="item.parentType" style="width: 0.96rem;" 
							   placeholder="关系" clearable>
					    <el-option v-for="item in parentMode" :key="item.value"
					      		   :label="item.name" :value="item.value">
					    </el-option>
					</el-select>
					&emsp;
					
					<label class="must">*</label>
					<label class="label">联系电话</label>
					<el-input v-model="item.phone" class="input phone" maxLength="11" clearable></el-input>
					
					&emsp;
					<label class="label">家长微信</label>
					<el-input v-model="item.wechat" class="input wechat" maxLength="20" clearable></el-input>
					<span class="add_btn" @click="addParent(index)"></span>
					<span class="reduce_btn" v-if="index!=0" @click="delParent(index)"></span>
				</div>
				
				<div class="row_4">
					<label class="must"></label>
					<label class="label">收货地址</label>
					<el-input v-model="param.studentUserAddressEntityList[0].receiverName" id="receiverName" clearable
						      style="width: 1.87rem;" placeholder="收件人" clearable></el-input>&nbsp;&nbsp;
					<el-input v-model="param.studentUserAddressEntityList[0].receiverPhone" id="receiverPhone" clearable
						      style="width: 1.87rem;" placeholder="联系电话" clearable maxLength="11"></el-input>&nbsp;&nbsp;
					<el-cascader v-model="cityValue" :props="defaultProps" style="width: 2.5rem;" placeholder="省市区"
								 clearable :options="citys" separator=""></el-cascader>&nbsp;&nbsp;
					<el-input v-model="param.studentUserAddressEntityList[0].address" id="address" clearable
							  style="width: 2.5rem;" placeholder="详细地址" clearable maxLength="50"></el-input>
				</div>
				
				<div class="row_5">
					<label class="must">*</label>
					<label class="label">渠道来源</label>
					<div class="channel_add" @click="openChannelAdd()"
						 :style="{visibility:(hasApi('channelAdd')?'visible':'hidden')}">新建渠道</div>
					<div class="channel_list">
						<div class="radio_group">
							<label class="radio" v-for="item,index in channelList" @click="param.channelId = item.clueChannelId">
								<span class="radio_circle" :class="item.clueChannelId==param.channelId? 'radio_active' : ''"></span>
								<span class="radio_name">{{item.name}}</span>
							</label>
						</div>
					</div>
				</div>
				
				<div class="row_6">
					<label class="must">*</label>
					<label class="label">意向校区</label>
					<el-select v-model="param.campusId" @change="campusChange"
							   class="input" placeholder="" filterable>
					    <el-option v-for="item in campusList" :key="item.campusId"
					      		   :label="item.name" :value="item.campusId">
					    </el-option>
					</el-select>
					&emsp;
					
					<label class="must">*</label>
					<label class="label">线索状态</label>
					<el-select v-model="param.clueStatus" id="clueStatus" class="input"
						       :disabled="true" placeholder="">
					    <el-option v-for="item in clueStatus" :key="item.value" :disabled="item.disabled"
					      		   :label="item.name" :value="item.value">
					    </el-option>
					</el-select>
					&emsp;
					
					<label class="label">咨询日期</label>
					<el-date-picker v-model="param.consultDate" value-format="yyyy-MM-dd"
						type="date" class="input" clearable :picker-options="pickerOptions">
				    </el-date-picker>
				</div>
				
				
				
				<div class="row_6" v-for="item,index in param.courseData">
					<label class="must"></label>
					<label class="label">课程意向</label>
					<el-select v-model="item.courseId" class="input courseId" 
						placeholder="" clearable filterable>
					    <el-option v-for="course in courseList" :key="course.courseId"
					              :label="course.courseName" :value="course.courseId">
					    </el-option>
					</el-select>
					
					&emsp;
					<label class="must"></label>
					<div class="radio_group">
						<label class="radio" v-for="intention in intentionMode" @click="item.intentionMode = (item.intentionMode == intention.value? '' : intention.value)">
							<span class="radio_circle" :class="intention.value==item.intentionMode? 'radio_active' : ''"></span>
							<span class="radio_name">{{intention.name}}</span>
						</label>
					</div>
					<span class="add_btn" style="margin-left: 0.4rem;" @click="addCourse(index)"></span>
					<span class="reduce_btn" @click="delCourse(index)"></span>
				</div>
				
				<div class="row_7">
					<label class="must"></label>
					<label class="label" style="">沟通内容</label>
					<el-input v-model="param.remark" id="remark" type="textarea" 
							  style="width: 9.61rem;vertical-align: top;" maxLength="100"></el-input>
					<div class="clue_important" @click="checkImport()">
						<span class="checkbox" :class="param.isMatter==1? 'checkbox_active':''"></span>
						<span>重要线索</span>
					</div>
				</div>
				
				<div class="row_8">
					<label class="must">*</label>
					<label class="label">采单员</label>
					<el-select v-model="param.collectUserId" class="input" filterable>
					    <el-option v-for="item in userList" :key="item.userId"
					              :label="item.nickName" :value="item.userId">
					    </el-option>
					</el-select>
					&emsp;
					
					<label class="must"></label>
					<label class="label">跟进人</label>
					<el-select v-model="param.executeUserId" id='executeUserId' class="input"
							   @change="executeChange" clearable filterable>
					    <el-option v-for="item in userList" :key="item.userId"
					              :label="item.nickName" :value="item.userId">
					    </el-option>
					</el-select>
					&emsp;
					
					<label class="label" style="width:1.13rem;">下次沟通日期</label>
					<el-date-picker v-model="param.nextVisitDate" value-format="yyyy-MM-dd"
						type="date" class="input" clearable :picker-options="pickerOptions2">
				    </el-date-picker>
				</div>
				
			</div>
			
			<div class="btn_div">
				<div class="btn_sure" @click="sure()">确 认</div>
				<div class="btn_cancel" @click="cancel()">取 消</div>
			</div>
		</div>
	</div>
</template>

<script>
import citys from "@/../static/citys.json"

var vm,dict,user;
var param = {
		realName : "",
		gender : "",
		kindergarten : "",
		birthday : "",
		channelId : "",
		campusId : "",
		consultDate : "",
		clueStatus : "",
		collectUserId : "",
		executeUserId : "",
		nextVisitDate : "",
		remark : "",
		isMatter : 0,
		parentData : [{ parentName : "", parentType : "", phone : "", wechat: ""}],
		courseData : [ { courseId : "", intentionMode : "" }],
		studentUserAddressEntityList : [{receiverName : "",receiverPhone : "",province:"",
		city : "", area : "", address : "", isUse : 1}],
		_wait : ""
};
export default {
	data : function() {
		return {
			show : false,
			open : false,
			visible : false,
			param : tool.clone(param),
			//列表数据
			userList : null,
			campusList : null,
			courseList : null,
			channelList : null,
			//数据字典
			parentMode : null,
			clueStatus : null,
			intentionMode : null,
			gradeMode : null,
			gender : null,
			//当前校区id
			campusId : null,
			today : null,
			//城市数据
			citys : [],
			cityValue : [],
			defaultProps: {
		        label: "label",
		        value: "label",
		        children: "children"
	      	},
	        pickerOptions : {  //日期有效性计算
				disabledDate : function(date) {
					return date > vm.today;
				}
			},
			pickerOptions2 : {  //日期有效性计算
				disabledDate : function(date) {
					return date < vm.today;
				}
			}
		}
	},
	watch : {
		"param.parentData" : {
			handler : function(list) {
				list.forEach(function(item) {
					item.phone = item.phone.replace(/[^\d]/g,'');
				})
			},
			deep: true
		},
		"param.studentUserAddressEntityList" : {
			handler : function(list) {
				list[0].receiverPhone = list[0].receiverPhone.replace(/[^\d]/g,'');
			},
			deep: true
		}
	},
	methods : {
		init : function() {
			vm.show = true;
			setTimeout(function() { 
				vm.open = true; 
				vm.visible = true;
			},1);
			//初始化数据
			vm.param = tool.clone(param);
			vm.param.collectUserId = user.userId;
			vm.param.executeUserId = user.userId;
			vm.param.clueStatus = vm.clueStatus[1].value;
			vm.param.campusId = vm.$store.state.campusId;
			
			//当前年月日
			var now = tool.DateToString(new Date(), "yyyy-MM-dd")
			vm.param.consultDate = now;
			vm.today = new Date(now +" 00:00:00");
//			vm.param.nextVisitDate = vm.today
			
			//加载校区相关列表数据
			vm.loadList();
			
		},
		cancel : function() {
			vm.open = false;
			setTimeout(function() {
				vm.show = false;
				vm.visible = false;
			},500);
		},
		executeChange : function() {
			vm.param.clueStatus = (vm.param.executeUserId? 2 : 1)
		},
		sure : function() { 
			//克隆新对象,防止转变后影响页面显示
			var p = tool.clone(vm.param);
			
			var a = p.studentUserAddressEntityList[0];
			var v = vm.cityValue;
			
			//城市数组转到参数中
			if(v.length>0) {
				a.province = v[0];
				a.city = v[1];
				a.area = v[2];
			} else {
				a.province = a.city = a.area = "";
			}
			
			//收货地址所有字段为空
			if(JSON.stringify(a) == JSON.stringify(param.studentUserAddressEntityList[0])) {
				p.studentUserAddressEntityList = [];
			}
			
			//验证规则
			var rules = [{
				judge : tool.judge("name",p.realName),
				focus : $("#clue_add #realName"),
				tips : tips.name
			}];
			
			p.parentData.forEach(function(item,index) {
				//家长姓名为空,或者符合姓名规范
				rules.push({
					judge : (!item.parentName) || tool.judge("name",item.parentName),
					focus : $("#clue_add .parentName input").eq(index),
					tips : tips.name
				});
				rules.push({
					judge : tool.judge("phone",item.phone),
					focus : $("#clue_add .phone input").eq(index),
					tips : tips.phone
				});
			});
			
			rules.push({
				judge : !a.receiverName ||  tool.judge("name",a.receiverName), //要么不填,要么符合规则
				focus : $("#clue_add #receiverName"),
				tips : tips.name
			});
			rules.push({
				judge : !a.receiverPhone ||  tool.judge("phone",a.receiverPhone), //要么不填,要么符合规则
				focus : $("#clue_add #receiverPhone"),
				tips : tips.phone
			});
			
			rules.push({
				judge : p.channelId,
				focus : null,
				tips : "请选择渠道来源"
			});
			
			var courseIds = [];
			var index = -1;
			//遍历意向课程和意向度
			for(let i = 0; i < p.courseData.length; i++) {
				index++;
				
				let item = p.courseData[i];
				//如果意向课程和意向度都没填,删除
				if(item.courseId=="" && item.intentionMode=="") {
					p.courseData.splice(i,1);
					i--;
					continue
				}
				//意向课程和意向度,一个填一个没填,不给通过
				if(item.courseId=="") {
					rules.push({
						judge : false,
						focus : $("#clue_add .courseId input").eq(index),
						tips : "请选择课程意向"
					});
					break;
				}
				if(item.intentionMode=="") {
					rules.push({
						judge : false,
						focus : $("#clue_add .courseId input").eq(index),
						tips : "请选择课程意向度"
					});
					break;
				}
				//遍历课程,判断是否重复
				if(courseIds.indexOf(item.courseId)<0) {
					courseIds.push(item.courseId);
				} else {
					rules.push({
						judge : false,
						focus : $("#clue_edit .courseId input").eq(index),
						tips : "请勿选择重复的课程"
					});
					break;
				}
			}
			
//			rules.push({
//				judge : p.remark,
//				focus : $("#clue_add #remark"),
//				tips : tips.blank
//			});
			
			//跟进中的线索，必须选跟进人
//			if(p.clueStatus == 2) {
//				rules.push({
//					judge : p.executeUserId,
//					focus : $("#clue_add #executeUserId"),
//					tips : "当前线索状态为跟进中，请选跟进人"
//				});
//			}
			//待跟进的线索，不允许有跟进人
//			if(p.clueStatus == 1) {
//				rules.push({
//					judge : !p.executeUserId,
//					focus : $("#clue_add #clueStatus"),
//					tips : "当前存在跟进人，线索状态不允许为待跟进"
//				});
//			}
			if(!tool.validate(rules)) {
				return;
			}
			//将对象的关联字段,无值的""转回0
			tool.change("",0,p,["grade","executeUserId","parentData.parentType"]);
			
			//如果是失效状态或者待跟进,设为非重要线索
			if(p.clueStatus==7 || p.clueStatus==1) {
				p.isMatter = 0;
			}
			
			api.clueAdd(p).then(function(data) {
				if(data.resultCode=="2000") {
					tool.message({ showClose: true, message: "新增成功", type: 'success'});
					vm.$emit('callback',data.clue);
					vm.cancel();
				}
				if(data.resultCode=="4024") {
					tool.message({ showClose: true, message: "该线索已添加到系统，请核实姓名和联系方式是否正确", type: 'warning'});
				}
			})
		},
		openChannelAdd : function() {
			//隐藏当前页面
//			vm.open = false;
//			vm.show = false;
//			vm.visible = false;
			//回调父页面,打开新建渠道页面
			vm.$emit('channelAdd', "clueAdd");
		},
		closeChannelAdd : function(state) {
			//显示页面
//			vm.show = true;
//			setTimeout(function() { 
//				vm.open = true; 
//				vm.visible = true;
//			},1);
			
			//渠道新增成功
			if(state == "ok") {
				//渠道列表
				api.channelList({campusId : vm.param.campusId}).then(function(data) {
					vm.channelList = data.list;
				});
			}
		},
		addParent : function(index) {
			//新增一个家长
			var item = { parentName : "", parentType : "", phone : "", wechat : "" };
			vm.param.parentData.splice(index+1, 0, item);
		},
		delParent : function(index) {
			//删除一个家长
			var list = vm.param.parentData;
			if(list.length == 1) {
				tool.message("至少需要1位家长信息");
			} else {
				list.splice(index,1);
			}
		},
		addCourse : function(index) {
			//新增一个意向课程
			var item = { courseId : "", intentionMode : ""};
			vm.param.courseData.splice(index+1, 0, item);
		},
		delCourse : function(index) {
			//删除一个意向课程
			var list = vm.param.courseData;
			if(list.length == 1) {
				list[0].courseId = "";
				list[0].intentionMode = "";
			} else {
				list.splice(index,1);
			}
		},
		checkImport : function() {
			vm.param.isMatter = (vm.param.isMatter=="0"?  "1" : "0");
		},
		campusChange : function(val) {
			//加载校区相关的列表
			vm.loadList();
		},
		loadList : function() {
			//重设校区
			var id = vm.param.campusId;

			//课程列表
			api.courseList({campusId : id}).then(function(data) {
				
				vm.courseList = data.list;
				var list = [];
				data.list.forEach(function(item) {
					list.push(item.courseId);
				})
				//遍历当前选中的课程列表
				var c = vm.param.courseData;
				for(var i=0; i<c.length; i++) {
					//如果不在新的列表中,则删除
					if(c[i].courseId && list.indexOf(c[i].courseId)<0) {
						c.splice(i,1);
						i--;
					}
					//如果列表被删光了,则加上默认的空行
					if(c.length==0) {
						c.push({ courseId : "", intentionMode : "" });
					}
				}
				
			});
			
			//渠道列表
			api.channelList({campusId : id}).then(function(data) {
				vm.channelList = data.list;
				vm.param.channelId = "";
			});
			
			//用户列表
			api.userListByCampus({campusId : id}).then(function(data) {
				vm.userList = data.userList;
				var list = [];
				data.userList.forEach(function(item) {
					list.push(item.userId);
				})
				if(list.indexOf(vm.param.executeUserId)<0) {
					vm.param.executeUserId = "";
				}
				
			});
		}
	},
	created : function() {
		vm = this;
		//获取用户和数据字典对象
		user = tool.getItem(lsKey.user,true);
		dict = tool.getItem(lsKey.dict,true);
		
		//从缓存设置初始数据
		vm.campusList = user.campusList;
		vm.parentMode = dict["parent_mode"];
		vm.clueStatus = dict["clue_status"];
		vm.gradeMode = dict["grade_mode"];
		vm.intentionMode = dict["intention_mode"];
		vm.gender = dict["gender"];
		
		vm.citys = citys;
		
		//设置失效状态不可点
		vm.clueStatus.forEach(function(item) {
			if(item.value==7) {
				item.disabled = true;
			}
		});
	},
}
</script>

<style lang="scss">
	#clue_add {
		.el-textarea__inner {
			height: 0.85rem;
			font-size: 0.16rem;
			font-family: "微软雅黑";
		}
		.el-cascader__label {
			font-size: 0.16rem;
			color: #666666;
			line-height: 0.38rem;
		}
	}
</style>
<style scoped src="@/style/module/dialog.css"></style>
<style scoped src="@/style/module/radio.css"></style>
<style scoped src="@/style/clue_manage/clue_add.css"></style>
<style scoped>
	.radio_group {
		line-height: 0.36rem;
	}
</style>
